package com.calculator.pmzvfk;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private StringBuilder num1 = new StringBuilder();
    private StringBuilder num2 = new StringBuilder();
    private String operation;
    private boolean isFirstNumber = true;
    private StringBuilder detail = new StringBuilder();
    private String currentOperation = null;

    private TextView detailTextView;
    private TextView resultTextView;
    private Button button_one;
    private Button button_two;
    private Button button_three;
    private Button button_four;
    private Button button_five;
    private Button button_six;
    private Button button_seven;
    private Button button_eight;
    private Button button_nine;
    private Button divideBtn;
    private Button multiplyBtn;
    private Button minusBtn;
    private Button addBtn;
    private Button percentBtn;
    private Button clearHistory_button;
    private Button button;
    private Button button_;
    private Button equalButton;
    private Button button_0;
    private Button button_00;
    private Button clearButton;
    private ImageButton backspaceButton;
    private Button btnGotoFastCalcGame;
    private String result;
    private String firstExpression = "";

    private String lastResult = "0";


    private ArrayList<String> history = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        detailTextView = findViewById(R.id.detailTextView);
        resultTextView = findViewById(R.id.resultTextView);
        clearButton = findViewById(R.id.clear_button);
        backspaceButton = findViewById(R.id.backspace);
        equalButton = findViewById(R.id.equalBtn);
        button_one = findViewById(R.id.button_one);
        button_two = findViewById(R.id.button_two);
        button_three = findViewById(R.id.button_three);
        button_four = findViewById(R.id.button_four);
        button_five = findViewById(R.id.button_five);
        button_six = findViewById(R.id.button_six);
        button_seven = findViewById(R.id.button_seven);
        button_eight = findViewById(R.id.button_eight);
        button_nine = findViewById(R.id.button_nine);
        divideBtn = findViewById(R.id.divideBtn);
        multiplyBtn = findViewById(R.id.multiplyBtn);
        minusBtn = findViewById(R.id.minusBtn);
        addBtn = findViewById(R.id.addBtn);
        percentBtn = findViewById(R.id.percentBtn);
        clearHistory_button = findViewById(R.id.clearHistory_button);
        button_ = findViewById(R.id.button_);
        button_0 = findViewById(R.id.button_0);
        button_00 = findViewById(R.id.button_00);

        initButton();

        btnGotoFastCalcGame = findViewById(R.id.gotoFastCalcGame_button);
        btnGotoFastCalcGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, FastCalculationActivity.class);
                startActivity(intent);
            }
        });

        if (history.isEmpty()) {
            history.add("No history");
            saveHistory();
        }

        clearHistory_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showClearHistoryConfirmation();
            }
        });

        // 在onCreate方法中添加按钮的点击事件监听
        Button historyButton = findViewById(R.id.history_button);
        historyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHistoryDialog();
            }
        });

        //清空
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detail.setLength(0);
                num1.setLength(0);
                num2.setLength(0);
                isFirstNumber = true;
                currentOperation = null;
                detailTextView.setText("0");
                resultTextView.setText("0");
                firstExpression = "";
                lastResult = "0"; // 重置上次计算结果
            }
        });


        Button equalButton = findViewById(R.id.equalBtn);
        equalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String expression = detailTextView.getText().toString();

                // 如果上一次结果不为零，则使用它
                if (!"0".equals(lastResult) && !expression.equals(firstExpression)) {
                    expression = lastResult + expression.substring(firstExpression.length());
                }

                firstExpression = expression; // 保存当前表达式以备后用

                if (expression.contains("÷")) {
                    expression = expression.replace("÷", "/");
                }
                if (expression.contains("×")) {
                    expression = expression.replace("×", "*");
                }

                result = calculateResult(expression);
                resultTextView.setText(result);

                // 保存这次的结果
                lastResult = result;
            }
        });

        // 删除按钮的点击事件处理
        backspaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detail.length() > 0) {
                    detail.deleteCharAt(detail.length() - 1);
                    if (detail.length() == 0) {
                        isFirstNumber = true;
                        detailTextView.setText("0");
                    } else {
                        detailTextView.setText(detail.toString());
                        System.out.println(detailTextView.getText());
                    }
                }
            }
        });

    }

    private String calculateResult(String expression) {
        try {
            Expression e = new ExpressionBuilder(expression).build();
            double result = e.evaluate();
            String historyEntry = firstExpression + " = " + result;
            updateHistory(historyEntry);
            return String.valueOf(result);
        } catch (Exception e) {
            return "Error"; // 或处理错误的其他方式
        }
    }

    private void updateHistory(String historyEntry) {
        if (!history.isEmpty() && "No history".equals(history.get(0))) {
            history.remove(0);
        }
        history.add(historyEntry);
        saveHistory();
    }

    private void initButton() {
        divideBtn.setOnClickListener(this::operationBtnClicked);
        multiplyBtn.setOnClickListener(this::operationBtnClicked);
        minusBtn.setOnClickListener(this::operationBtnClicked);
        addBtn.setOnClickListener(this::operationBtnClicked);
        percentBtn.setOnClickListener(this::operationBtnClicked);


        button_one.setOnClickListener(this::numberBtnClicked);
        button_two.setOnClickListener(this::numberBtnClicked);
        button_three.setOnClickListener(this::numberBtnClicked);
        button_four.setOnClickListener(this::numberBtnClicked);
        button_five.setOnClickListener(this::numberBtnClicked);
        button_six.setOnClickListener(this::numberBtnClicked);
        button_seven.setOnClickListener(this::numberBtnClicked);
        button_eight.setOnClickListener(this::numberBtnClicked);
        button_nine.setOnClickListener(this::numberBtnClicked);
        button_.setOnClickListener(this::numberBtnClicked);
        button_0.setOnClickListener(this::numberBtnClicked);
        button_00.setOnClickListener(this::numberBtnClicked);
    }

    private void operationBtnClicked(View view) {
        if (num1.length() > 0) {
            isFirstNumber = false;
            operation = view.getTag().toString();
            if (currentOperation == null) {
                detail.append(getOperation(operation));
                currentOperation = operation;
            } else {
                detail.replace(detail.length() - 1, detail.length(), getOperation(operation));
            }
            detailTextView.setText(detail.toString());
        }
    }

    private void numberBtnClicked(View view) {
        String numString = view.getTag().toString();
        detail.append(numString);
        detailTextView.setText(detail.toString());
        if (currentOperation != null) {
            currentOperation = null;
        }
        if (isFirstNumber) {
            num1.append(numString);
        } else {
            num2.append(numString);
        }
    }

    private String getOperation(String tag) {
        switch (tag) {
            case "1":
                return "÷";
            case "2":
                return "×";
            case "3":
                return "-";
            case "4":
                return "+";
            case "5":
                return "%";
            default:
                return "";
        }
    }

    private void saveHistory() {
        SharedPreferences prefs = getSharedPreferences("CalculatorHistory", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        // 将ArrayList转换为JSON
        Gson gson = new Gson();
        String json = gson.toJson(history);
        editor.putString("history", json);
        editor.apply();
    }

    private void loadHistory() {
        SharedPreferences prefs = getSharedPreferences("CalculatorHistory", MODE_PRIVATE);
        // 获取JSON格式的历史记录
        String json = prefs.getString("history", null);
        if (json != null) {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<String>>() {
            }.getType();
            history = gson.fromJson(json, type);
        } else {
            history = new ArrayList<>();
        }
    }

    // 实现showHistory方法
    private void showHistoryDialog() {
        loadHistory();
        // 创建HistoryDialogFragment实例并传递历史记录数据
        HistoryDialogFragment historyDialog = new HistoryDialogFragment(history);

        // 显示对话框
        historyDialog.show(getSupportFragmentManager(), "history_dialog");
    }

    private void clearHistory() {

        // 获取SharedPreferences对象
        SharedPreferences prefs = getSharedPreferences("CalculatorHistory", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // 移除历史记录键
        editor.remove("history");

        // 提交更改
        editor.apply();

        // 同时清空当前历史记录列表
        if (history != null) {
            history.clear();
        }
    }

    private void showClearHistoryConfirmation() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Clear history");
        builder.setMessage("Are you sure you want to clear all history？");

        // 确定按钮
        builder.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearHistory();
                history.add("No history");
                saveHistory();
                Toast.makeText(MainActivity.this, "The history has been cleared!", Toast.LENGTH_SHORT).show();
            }
        });

        // 取消按钮
        builder.setNegativeButton("Cancel", null);

        AlertDialog dialog = builder.create();
        dialog.show();
    }


}
